package request;

import org.omg.CORBA.Request;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Map;

/**
 * 演示使用 request 对象获取请求的参数，包括 Get 请求的查询字符串和 Post 请求的请求体。
 */
public class RequestParameters extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writeParameters(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writeParameters(req,resp);
    }

    //todo 重构，提取一个公用方法
    private void writeParameters(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = resp.getWriter();
        Enumeration<String> params = req.getParameterNames();
        while (params.hasMoreElements()) {
            String param = params.nextElement();
            writer.printf("%1$s = %2$s%n",param,req.getParameter(param));
        }
    }
}
